<template>
  <div class="webapp">
    <BasicContainer>
      <FyFormDesign :options="option" @submit="handleSubmit" />
    </BasicContainer>
  </div>
</template>

<script>
  import { getForm, postForm } from '@/api/gen/gen'
  import { removeStore } from '@/util/store'

  function stringifyWithFunctions(object) {
    return JSON.stringify(object, (key, val) => {
      if (key === 'onLoad') {
        return `(${val})`
      }
      return val
    })
  }

  export default {
    data() {
      return {
        option: {
          column: []
        }
      }
    },
    created() {
      this.getFormInfo()
    },
    methods: {
      handleSubmit(json) {
        const params = this.$route.query
        if (this.$isBlank(params)) {
          return false
        }
        const result = stringifyWithFunctions(json)

        // console.log('写入res ', result)
        postForm(result, params.tableName, params.dsName).then(response => {
          this.$message.success('生成并保存成功')
          const cacheKey = `${params.dsName}_${params.tableName}_config`
          removeStore(cacheKey)
        })
      },
      getFormInfo() {
        const params = this.$route.query
        if (this.$isBlank(params)) {
          return false
        }
        getForm(params.tableName, params.dsName).then(response => {
          if (!this.$isBlank(response.data.data)) {
            const parseWithFunctions = obj => {
              return JSON.parse(obj, (key, val) => {
                if (key === 'onLoad') {
                  // eslint-disable-next-line no-new-func
                  return new Function(`return ${val};`).apply(this)
                }
                return val
              })
            }
            this.option = parseWithFunctions(response.data.data)
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  .webapp {
    position: relative;
    width: 100%;
    height: 100%;
    background-color: #fff;

    .form-designer {
      height: 800px;
      overflow-y: scroll;
    }

    .form-designer .widget-config-container .el-tabs__header {
      position: relative;
    }
  }
</style>
